package com.example.lib_image.glide.glide

import android.content.Context
import android.os.Environment
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory
import com.bumptech.glide.load.engine.cache.LruResourceCache
import com.bumptech.glide.load.engine.cache.MemorySizeCalculator
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.AppGlideModule
import okhttp3.Cache
import okhttp3.OkHttpClient
import java.io.File
import java.io.InputStream

class CustomGlideModule:AppGlideModule() {
    override fun applyOptions(context: Context, builder: GlideBuilder) {

        //计算使用多大的内存空间
       val glideMemorySize= MemorySizeCalculator.Builder(context).build().memoryCacheSize/6L

        //设置内存大小
        builder.setMemoryCache(LruResourceCache(glideMemorySize))

        //设置磁盘大小(默认250)
        builder.setDiskCache(InternalCacheDiskCacheFactory(context,"glide_disk_cache",300*1024*1024))
    }

    /**
    * 自定义网络缓存大小
    * Glide网络采用Okhttp实现
    * */
    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        val builder=OkHttpClient.Builder()
        //先考虑外部SD卡，如果没有再考虑内存SD卡
        val externalDir =Environment.getExternalStorageDirectory()

        var cacheDir = if(externalDir.exists()){
                "${externalDir.absolutePath}/glideCache"
            }else{
                "${context.externalCacheDir?.absolutePath}/glideCache"
            }
        val cacheFile = File(cacheDir)

        var cacheSize = 50*1024*1024L
        if(externalDir.exists()&& externalDir.totalSpace > 0L){
            cacheSize =externalDir.totalSpace / 8L
        }else{
            cacheSize = context.externalCacheDir?.totalSpace?.div(8L)?:10*1024*1024L
        }
        val networkCache = Cache(cacheFile,cacheSize)


        //设置网络缓存目录
        builder.cache(networkCache)

        val newOkHttpClient = builder.build()
        registry.replace(GlideUrl::class.java,InputStream::class.java,OkHttpUrlLoader.Factory(newOkHttpClient))


    }
}